package net.tplusplus.rules.runner;

import net.tplusplus.rules.runner.rao.Fact;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;

import java.util.List;

import java.io.File;


public class KnoveledgeBaseRunner {

	//private KnowledgeBase knovledgeBase;
	public void executeInStatefulSession(String ruleSetFileName, List<Fact> facts)
	{
		KnowledgeBase kBase;
		try {
			kBase = this.getKnowledgeBase(ruleSetFileName);
			StatefulKnowledgeSession session = kBase.newStatefulKnowledgeSession();
			for(Fact f: facts)
				session.insert(f);
			
			session.fireAllRules();
			session.dispose();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private KnowledgeBase getKnowledgeBase(String ruleSetFileName) throws Exception
	{
		KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
		
		kBuilder.add(ResourceFactory.newFileResource(new File(ruleSetFileName)), ResourceType.DRL);
		KnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
		kBase.addKnowledgePackages(kBuilder.getKnowledgePackages());
		return kBase;
		
	}
}
